import {
    insert,query,callFunction,del_mult, _,del, update
} from './index'

// 创建组件
export const insertAssembly_sort = (data) => {
    return insert({
        table: 'assembly_sort',
        data
    })
}
// 查询组件
export const queryAssembly_sort = async () => {
    const res = await callFunction('query_assembly_sort')
    return res.result
}
// 删除组件
export const deleteAssembly_sort = (_id) => {
    return del({
        table: 'assembly_sort',
        _id
    })
}

// 更新组件最新版本
export const updateAssembly_sort_version = async (_id) => {
    const result = await queryAssembly(_id)
    const version = result.length > 0 ?result[0].version : ''
    await update({
        table: "assembly_sort",
        _id,
        data: {
            version
        }
    })
}

// 版本是否已存在
export const isExistVersion = async (assembly_sort_id, version) => {
    const result = await query({
        table: 'assembly',
        data: {
            assembly_sort_id,
            version
        }
    })
    return result.length > 0
}

// 比较版本是否更新
const compareVersion = (version1, version2) => {
    let v1 = version1.split(".");
    let v2 = version2.split(".");
    
    for (let i = 0; i < v1.length; i++) {
        if (parseInt(v1[i]) > parseInt(v2[i])) return true;
        if (parseInt(v1[i]) < parseInt(v2[i])) return false;
    }
    
    if (v1.length < v2.length) return false;
    if (v1.length > v2.length) return true;
    
    return false;
}
export const isLastest = async (assembly_sort_id, version) => {
    const result = await query({
        table: 'assembly',
        data: {
            assembly_sort_id
        }
    })
    const lastest = result[0] ? result[0].version : ''
    const res =  lastest ? compareVersion(version, lastest) : true
    return res ? '' : lastest
}

// 添加版本
export const insertAssembly = (data) => {
    return insert({
        table: 'assembly',
        data
    })
}
// 查询版本
export const queryAssembly = (assembly_sort_id) => {
    return query({
        table: 'assembly',
        data: {
            assembly_sort_id
        }
    })
}
// 删除版本
export const delAssembly = (assembly_sort_id, arr) => {
    return del_mult({
        table: 'assembly',
        data: {
            assembly_sort_id,
            version: _.in(arr)
        }
    })
}

// 删除组件版本文件
export const deleteAssemblyFile = (dir) => {
    callFunction('delete_assembly', {
        dir
    })
}

// 组件分类
// 添加版本
export const insertAssemblyClassify = (data) => {
    return insert({
        table: 'assembly_classify',
        data
    })
}
// 查询版本
export const queryAssemblyClassify = () => {
    return query({
        table: 'assembly_classify'
    })
}